function demodulated_bits = demodulate_symbols(despread_symbols, modulation_type)
% demodulate_symbols - 对解扩后的符号进行解调
%
% 输入参数:
%   despread_symbols - 解扩后的符号
%   modulation_type  - 调制类型: 'BPSK', 'QPSK', 'QAM16'
%
% 输出参数:
%   demodulated_bits - 解调后的比特流

switch upper(modulation_type)
    case 'BPSK'
        % BPSK解调: 实部>0 -> 1, 实部<0 -> 0
        demodulated_bits = real(despread_symbols) > 0;
        
    case 'QPSK'
        % QPSK解调: 每个复符号解调为两个比特
        num_symbols = length(despread_symbols);
        demodulated_bits = zeros(1, num_symbols * 2);
        
        % QPSK星座点
        constellation = [(-1-1i)/sqrt(2), (-1+1i)/sqrt(2), (1-1i)/sqrt(2), (1+1i)/sqrt(2)];
        bit_mappings = [0 0; 0 1; 1 0; 1 1];  % 对应的比特映射
        
        for i = 1:num_symbols
            % 找到最近的星座点
            [~, idx] = min(abs(despread_symbols(i) - constellation));
            
            % 获取对应的比特对
            bit_pair = bit_mappings(idx, :);
            
            % 存储解调后的比特
            demodulated_bits(2*i-1:2*i) = bit_pair;
        end
        
    case 'QAM16'
        % 16QAM解调: 每个复符号解调为四个比特
        num_symbols = length(despread_symbols);
        demodulated_bits = zeros(1, num_symbols * 4);
        
        % 对每个符号进行解调
        for i = 1:num_symbols
            symbol = despread_symbols(i) * sqrt(10);  % 反归一化
            
            % 提取实部和虚部
            real_part = real(symbol);
            imag_part = imag(symbol);
            
            % 解调第一位: 实部正负
            demodulated_bits(4*i-3) = real_part > 0;
            
            % 解调第二位: 实部幅度
            demodulated_bits(4*i-2) = abs(real_part) < 2;
            
            % 解调第三位: 虚部正负
            demodulated_bits(4*i-1) = imag_part > 0;
            
            % 解调第四位: 虚部幅度
            demodulated_bits(4*i) = abs(imag_part) < 2;
        end
        
    otherwise
        error('不支持的调制类型: %s', modulation_type);
end

end 